package com.hfh.io;

import org.junit.Test;

import java.io.*;

public class InputStreamDemo {
    @Test
    public void closeDemo1() throws IOException {
        try(InputStream is = new FileInputStream("file\\note.txt")) {
            //代码体
        }
    }

    @Test
    public void closeDemo() throws IOException {
        InputStream is = new FileInputStream("file\\note.txt");
        is.close();
    }

    @Test
    public void test3() throws IOException {
        InputStream is = new FileInputStream("file\\note.txt");

        /*
        每次在读取数据到字节数组里面, 不要直接创建字符串,
        把数组里面的字节保存到内存里, 当所有的字节都读取完毕, 所有的数据都在内存
        最终把内存里面字节数组一次性创建字符串对象
         */
        // byte[] bys = new byte[6];
        // 字节数组一般习惯指定长度 1024, 刚好是1kb
        byte[] bys = new byte[1024];
        // 往内存里面写数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int len;// 每次读取到数组里的字节数
        while ((len = is.read(bys)) != -1) {
            baos.write(bys, 0, len);
        }

        // String result = new String(baos.toByteArray());
        // 从写了toString方法, 使用内部数据创建String并返回
        String result = baos.toString();
        System.out.println(result);


    }

    @Test
    public void test1() throws IOException {
        InputStream is = new FileInputStream("file\\a.txt");
        int len;
        byte[] arr = new byte[3];
        while ((len = is.read(arr)) != -1){
            String str = new String(arr,0,len);
            System.out.print(str);
        };
    }

    @Test
    public void test() throws IOException {
        InputStream is = new FileInputStream("file\\a.txt");
//        System.out.println((char) is.read());
//        System.out.println((char) is.read());
        int data;
        while ((data = is.read()) != -1){
            System.out.print((char) data);
        };
    }
}
